﻿using Owin;
using System;
using System.Web.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;

namespace King.Box.Owin
{
    public class AppServer
    {
        private readonly Semaphore _sem = new Semaphore(0, 1);

        public void Start(int port, Action<IAppBuilder, HttpConfiguration> action)
        {
            this.Start(port, null, action);
        }

        public void Start(int port, HttpConfiguration config)
        {
            this.Start(port, config, null);
        }

        public void Start(int port, HttpConfiguration config, Action<IAppBuilder, HttpConfiguration> action)
        {
            StartOptions options = new StartOptions($"http://*:{ port }");

            Task startTask = Task.Factory.StartNew(x =>
            {
                using (WebApp.Start(options, Startup.GetInstance().Configuration(config, action)))
                {
                    this._sem.WaitOne();
                }
            }, TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent);

            Action<Task> task = (Task runTask) =>
            {
                if (!runTask.IsFaulted)
                    return;

                Console.WriteLine($"Message:{ runTask.Exception.Message },InnerException:{ runTask.Exception.InnerException }");
            };

            startTask.ContinueWith(task);
        }

        public void Stop()
        {
            this._sem.Release();
        }
    }
}
